using UnityEngine;
using UnityEngine.EventSystems;

namespace Demo2048
{
    public enum MoveDirection
    {
        Left,
        Right,
        Up,
        Down
    }

    public class GameController : MonoBehaviour, IDragHandler, IPointerDownHandler
    {
        void Start()
        {
            change = false;
            this.motion = transform.GetComponent<Motion>();
            pRTF = transform.parent.transform as RectTransform;
        }

        public void OnDrag(PointerEventData eventData)
        {
            if (!change) return;

            Vector2 offset = eventData.position - pos;

            float x = Mathf.Abs(offset.x);
            float y = Mathf.Abs(offset.y);
            MoveDirection? dir = null;

            if (x > y && x > 50)
            {
                dir = offset.x > 0 ? MoveDirection.Right : MoveDirection.Left;
            }
            else if (x < y && y > 50)
            {
                dir = offset.y > 0 ? MoveDirection.Up : MoveDirection.Down;
            }

            if (dir != null)
            {
                change = false;
                Motion.GameRes ret = this.motion.Move(dir.Value);
                ChangePanel(ret);
            }
        }

        void ChangePanel(Motion.GameRes ret)
        {
            if (ret == Motion.GameRes.Failure)
            {
                pM.ChangePanel(PanelManage.PanelType.Failure);
            }
            else if (ret == Motion.GameRes.Success)
            {
                pM.ChangePanel(PanelManage.PanelType.Success);
            }
        }

        void ChangeToMain()
        {
            pM.ChangePanel(PanelManage.PanelType.Main);
        }

        public void OnPointerDown(PointerEventData eventData)
        {
            change = true;
            pos = eventData.position;
        }

        bool change;
        Motion motion;
        Vector2 pos;
        RectTransform pRTF;
        public PanelManage pM;
    }
}